#include "qtc_alarm_core/AlarmEvent.h"
#include "qtc_alarm_core/JsonUtil.h"

#include <QJsonArray>

namespace qtc_alarm_core {

QJsonObject AlarmEvent::toJson() const {
  QJsonObject obj;
  obj["type"] = type;
  obj["config"] = config;
  obj["pv"] = pv;
  obj["root"] = root;
  obj["severity"] = severity;
  obj["message"] = message;
  obj["state"] = state;
  obj["time"] = JsonUtil::toIso8601(time_epoch_ms);
  obj["time_epoch_ms"] = static_cast<double>(time_epoch_ms);
  obj["user"] = user;
  obj["host"] = host;
  obj["command"] = command;
  QJsonArray tag_arr;
  for (const auto& t : tags) tag_arr.push_back(t);
  obj["tags"] = tag_arr;
  return obj;
}

AlarmEvent AlarmEvent::fromJson(const QJsonObject& obj) {
  AlarmEvent ev;
  ev.type = obj.value("type").toString();
  ev.config = obj.value("config").toString();
  ev.pv = obj.value("pv").toString();
  ev.root = obj.value("root").toString();
  ev.severity = obj.value("severity").toString();
  ev.message = obj.value("message").toString();
  ev.state = obj.value("state").toString();
  ev.time_epoch_ms = obj.value("time_epoch_ms").toVariant().toLongLong();
  ev.user = obj.value("user").toString();
  ev.host = obj.value("host").toString();
  ev.command = obj.value("command").toString();
  if (obj.contains("tags") && obj.value("tags").isArray()) {
    const auto arr = obj.value("tags").toArray();
    for (const auto& v : arr) ev.tags << v.toString();
  }
  return ev;
}

} // namespace qtc_alarm_core
